import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:top_foundation/utils/util.dart';

class IImage {
  static Widget net({
    String? url,
    String? placeHolder,
    double? width,
    double? height,
    Color? color,
    BoxFit fit = BoxFit.contain,
    Widget Function(String, Error)? errorBuilder,
  }) {
    Widget buildErrorWidget(String? url, Object? error) {
      if (errorBuilder == null) return SizedBox(width: width, height: height);
      return errorBuilder(
        url ?? '无资源',
        error as Error? ?? StateError('无资源'),
      );
    }

    Widget buildPlaceHolder() {
      if (placeHolder == null) return buildErrorWidget(url, null);
      return Image.asset(
        placeHolder,
        width: width,
        height: height,
        fit: fit,
        color: color,
      );
    }

    if (url == null) {
      return buildPlaceHolder();
    }

    if (!url.startsWith('http')) {
      if (url.startsWith('file')) {
        return Image.file(
          File(url),
          width: width,
          height: height,
          fit: fit,
        );
      }

      return Image.asset(
        url,
        width: width,
        height: height,
        fit: fit,
      );
    }

    return CachedNetworkImage(
      imageUrl: url,
      placeholder: (context, url) {
        return buildPlaceHolder();
      },
      errorWidget: (context, url, error) => buildErrorWidget(url, error),
      width: width,
      height: height,
      fit: fit,
      color: color,
    );
  }

  static DecorationImage decoration({
    String? url,
    String? placeHolder,
    Color? color,
    BoxFit fit = BoxFit.contain,
    ImageProvider? errorWidget,
  }) {
    ImageProvider buildPlaceHolder() {
      return AssetImage(
        placeHolder!,
      );
    }

    ImageProvider buildImage() {
      if (url == null) return buildPlaceHolder();

      if (!url.startsWith('http')) {
        if (url.startsWith('file')) {
          return FileImage(File(url));
        }
        return AssetImage(url);
      }
      return CachedNetworkImageProvider(url);
    }

    return DecorationImage(
      image: buildImage(),
      fit: fit,
    );
  }
}
